package filter;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import util.controllerUtils.FrontStyleCodeUtil;
import controllers.item.LoginDisplay;
import controllers.session.LoginSession_WebSocketSession;
import core.login.LoginSession_WebSocketSessionInterface;

public class PowerFilter extends OncePerRequestFilter {
	// filter也是单例的
	private int test = 88;
	// 不过滤的uri
	// private final String[] filterUrls = new String[] { "/images", "/js",
	// "/css", "error.vm", "404.vm", "500.vm", "testLogin",
	// "/login/login", "/login/loginPage" };
	private LoginSession_WebSocketSessionInterface loginSession_WebSocketSessionInterface = LoginSession_WebSocketSession
			.getSession();

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		MDC.put("url", request.getRequestURI());
		if (filterUrl(request.getRequestURI())) {
			if (loginFilter(request) == false) {
				response.sendRedirect("http://localhost:8080/playViews/login/loginPage");
			}
		}
//		Map map = MDC.getContext();
//		if (map != null) {
//			map.clear();
//		}
		setPageStyle(request, response, filterChain);
		filterChain.doFilter(request, response);
	}

	/**
	 * 不需要进行过滤的url
	 * 
	 * @param uri
	 * @return
	 */
	private boolean filterUrl(String url) {
		for (Url var : Url.values()) {
			if (url.indexOf(var.toString()) != -1) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是否为Ajax请求
	 * 
	 * @param request
	 * @return 是true, 否false
	 * @see [类、类#方法、类#成员]
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}

	/**
	 * 设置界面样式
	 * 
	 * @param request
	 * @param response
	 * @param filterChain
	 * @throws IOException
	 * @throws ServletException
	 */
	private void setPageStyle(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {

		FrontStyleCodeUtil fs = FrontStyleCodeUtil
				.getFrontStyleCodeUtilEntity();
		String frontStyle = FrontStyleCodeUtil.quoteStyle(
				fs.getBootstrap_min_css(), fs.getBootstrap_min_js(),
				fs.getBootstrap_theme_min_css(), fs.getJquery_min_js());
		// model.addAttribute("FrontStyle",
		// FrontStyleCodeUtil.quoteStyle(fs.getBootstrap_min_css(),fs.getBootstrap_theme_min_css(),fs.getBootstrap_min_js()));
		// String var=
		// FrontStyleCodeUtil.quoteStyle(fs.getDateTimePicker_Bootstrap_bootstrap_datetimepicker_fr_js(),
		// fs.getDateTimePicker_Bootstrap_bootstrap_datetimepicker_js(),
		// fs.getDateTimePicker_Bootstrap_bootstrap_datetimepicker_min_css(),
		// fs.getDateTimePicker_Bootstrap_bootstrap_min_css(), fs
		// .getJquery_min_js(), fs
		// .getBootstrap_datetimepicker_zh_CN_js());

		request.setAttribute("FrontStyle", frontStyle);

	}

	/**
	 * 登陆成功后每个url请求都要检测其session的login加密id是否等于从页面发送过来的lid
	 * 防止浏览器出错服务器生成新session，在页面放sid从后端获取登录成功后保存的sessionid
	 * ，再在该session拿到当前登录账号信息login实体
	 * 
	 * @param request
	 * @return
	 */
	private boolean loginFilter(HttpServletRequest request) {
		String url = request.getRequestURI();
		String urlParams[] = url.split("/");
		String sid = urlParams[2];
		String lid_String = urlParams[3];
		if (sid == null)
			return false;
		long lId;
		try {
			lId = Long.parseLong(lid_String);
		} catch (Exception e) {
			return false;
		}
		HttpSession httpSession = loginSession_WebSocketSessionInterface
				.getHttpSessionBySid(sid);
		if (httpSession == null)
			return false;
		LoginDisplay login = (LoginDisplay) httpSession.getAttribute("login");
		if (login == null)
			return false;
		if (lId != login.getEncryptionId()) {
			return false;
		}
		try {
			request.setAttribute("lid", login.setABAndGetId());
			request.setAttribute("sid", sid);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}
